import { animate } from '@/utils/dom';

const seriesRegExp = /^cq\-overlay$/;

class OverlayClass {
	el = null; // 元素
	series = []; // 组件系列名
	constructor(params) {
		if (params.element) {
			this.el = document.querySelector(params.element);
			if (this.el) {
				this.el.classList.forEach((cls) => {
					const pass = seriesRegExp.test(cls);
					if (pass) this.series.push(cls);
				});
			}
		}
		if (params.onClose) {
			this.onClose = params.onClose;
		}
		this.bindDefaultEvents(params);
	}

	bindDefaultEvents(params) {
		this.el.cqDefaultEvent = true; // 告诉 cquery 该元素已设置默认事件
		this.el.addEventListener('click', () => {
			this.close();
		});
	}

	show() {
		this.el.classList.add('show');
		animate(this.el, {
			style: 'opacity',
			target: 1,
      speed: 0.1,
		});
	}

	close() {
		animate(this.el, {
			style: 'opacity',
			target: 0,
      speed: 0.1,
			callback: () => {
				this.el.classList.remove('show');
				if (this.onClose) {
					this.onClose();
				}
			},
		});
	}
}

const Overlay = {
	create(params) {
		return new OverlayClass(params);
	},
};

export default Overlay;
